from examples.rest import TraineRestClient, TraineRestConnection
import sounddevice
import asyncio

async def tts_stream_pipe(filepath:str, token:str, client:TraineRestClient, connect:TraineRestConnection):
    async for nparr, word in client.speech_stream_pipe(filepath, connect, token):
        try:
            print('word: %s, numpy len:%d' % (word, len(nparr)))
            sounddevice.play(data=nparr, samplerate=16000, blocking=True)
            await asyncio.sleep(0.1)
        except Exception:
            pass

if __name__ == "__main__":
    client: TraineRestClient = TraineRestClient('http://localhost:9090/api/v1', 'http://localhost:9090/auth',
                                                'xiaofanku@live.cn', 'admin888')
    loop = asyncio.get_event_loop()
    try:
        with client.connection() as conn:
            token = client.create_speech('English', conn)
            print('create speech stream token:%s' % token)
            if token:
                loop.run_until_complete(tts_stream_pipe('./oldmansea.txt', token, client, conn))
    except Exception as exp:
        print('exception: %s, message: %s' % (repr(exp), str(exp)))

    print('asyncio start lose')
    loop.close()

    print('client start close')
    client.close()